# coding=utf-8

"""
copyright (c) 2009, paketka@gmail.com et. al
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

	* Redistributions of source code must retain the above copyright notice,
	  this list of conditions and the following disclaimer.

	* Redistributions in binary form must reproduce the above copyright notice,
	  this list of conditions and the following disclaimer in the documentation
	  and/or other materials provided with the distribution.

	* Neither the name of the <ORGANIZATION> nor the names of its contributors
	  may be used to endorse or promote products derived from this software
 	  without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import datetime
import math
import re

from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django.template import RequestContext
from django.http import HttpResponse
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.utils.translation import ugettext as _
from django.http import Http404
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.core.cache import cache

from psp.models import *
from GChartWrapper import *
from utils.charts import *
from utils.fetcher import fetchStenoProto, fixStr
from justice.views import getAuthToken


def get_recyclation_graph(terms):
	termStats = range(terms.count())
	qs = Person.objects.all()

	for mp in qs:
		elects = Membership.objects.filter(
					person = mp,
					group__type__exact = 'PARLAMENT',
					post__iregex = '.*POSLAN.*'
				).count()
		if elects > 0:
			elects -= 1
			try:
				termStats[elects] += 1
			except:
				print '%s %s' % (mp.name, mp.surname)
				for e in Membership.objects.filter(
					person = mp,
					group__type__exact = 'PARLAMENT',
					post__iregex = '.*POSLAN.*'
				):
					print '%s' % e.post
					print e.start, '-', e.end
				raise
	count = qs.count()
	
	gData = []
	for t in termStats:
		i = ((1.0 * t) / count) * 100.0
		gData.append(i)

	graph = VerticalBarGroup(gData)
	graph.color('777777')
	s = ''
	for i in range(terms.count()):
		s += str(i) + '|'

	
	graph.title(_(u'Recyklace [%]'))

	graph.axes.type('xxyt')
	graph.axes.label(0, s)
	graph.axes.label(1, u'', u'', _(u'počet recyklací'))
	graph.axes.label(2, get_axis(range(0, 100, 20)) + u'%')
	graph.axes.label(3, get_axis(termStats))

	return graph


def get_recyclation_for_term(term):
	mpsInTerm = Person.objects.getPersonsOrderByName(term = term)
	recycled = 0
	zombies = 0
	freshmen = 0
	greenhorns = 0
	if term == TermOfOffice.objects.all()[0]:
		recycled = 0
		zombies = 0
		freshmen = 100.0
		greenhorns = len(mpsInTerm)
	else:
		zombies = 0
		for mp in mpsInTerm:
			mpMembership = Membership.objects.filter(
								person = mp,
								group__type__exact = 'PARLAMENT',
								post__iregex = '.*POSLAN.*'
							)
			if mpMembership.count() > 1:
				zombies += 1
	
		recycled = get_percents(zombies, len(mpsInTerm))
		freshmen = 100.0 - recycled
		greenhorns = len(mpsInTerm) - zombies

	return recycled, freshmen, zombies, greenhorns
	

def get_recycled_pie_graph(term):
	recycled, freshmen, zombies, greenhorns = get_recyclation_for_term(term)
	retVal = Pie3D([ recycled / 100.0, freshmen / 100.0 ])
	retVal.label(
			_(u'Veteráni') + ' %d' % int(zombies),
			_(u'Zelenáči') + ' %d' % int(greenhorns)
		)
	retVal.color('005500', '00aa00') 

	yearStart = term.yearStart
	yearEnd = term.yearEnd
	if yearEnd == '':
		yearEnd = str(datetime.datetime.today().year)
	retVal.title(_(u'Zelenáči vs. Veteráni') + '(%s - %s)' % (yearStart, yearEnd))

	retVal.size(330, 130)

	return retVal


def get_recyclation_trend_graph(terms):
	recycled = []
	freshmen = []
	absRecycled = []
	recycled.append(0.0)
	freshmen.append(100.0)
	absRecycled.append(0)
	for t in terms[1:]:
		recycld, frshmn, zombies, greenhorns = get_recyclation_for_term(t)
		absRecycled.append(zombies)
		recycled.append(recycld)
		freshmen.append(frshmn)

	graph = VerticalBarStack([recycled, freshmen])
	graph.title(_(u'Recyklační trend'))
	graph.color('005500', '00AA00')
	graph.legend(_(u'Veteráni'), _(u'Zelenáči'))
	graph.axes.type('xxty')
	startY, endY = get_year_rng_axes(terms)
	graph.axes.label(0, startY)
	graph.axes.label(1, endY)
	graph.axes.label(2, get_axis(absRecycled))
	graph.axes.label(3, get_axis(range(0, 100, 20)) + u'%')

	return graph


def get_mf_ratio_graph(terms):
	termStats = []
	i = 0

	females = []
	males = []
	for t in terms:
		g = Group.objects.get(type__iexact = 'PARLAMENT', term = t)
		male, female = g.getMfRatio()
		pm = get_percents(male, male + female)
		pf = get_percents(female, male + female)
		males.append(pm)
		termStats.append(pf)
		females.append(female)

	graph = VerticalBarStack([females, males])
	graph.title(_(u'Počet žen v parlamentu'))
	graph.color('770000', '000077')
	graph.legend(_(u'Ženy'), _(u'Muži'))
	graph.axes.type('xxyt')
	
	startY, endY = get_year_rng_axes(terms)
	graph.axes.label(0, startY)
	graph.axes.label(1, endY)
	graph.axes.label(2, get_axis(range(0, 100, 20)) + u'%')
	graph.axes.label(3, get_axis( map(lambda f: "%d" % int(f), females) ))

	return graph


def get_mp_orgs_graph(terms):
	termStats = []

	for t in terms:
		termStats.append(
			Group.objects.filter(term = t).count()
		)
	
	maxGroupCount = max(termStats)
	yRange = ((maxGroupCount / 20) + 1) * 20
	bars = map(lambda x: (x * 1.0 / yRange) * 100.0, termStats)
	graph = VerticalBarGroup(bars)
	graph.color('777777')
	graph.title(_(u'Počet parl. organizací'))
	graph.axes.type('xxyt')
	startY, endY = get_year_rng_axes(terms)
	graph.axes.label(0, startY)
	graph.axes.label(1, endY)
	graph.axes.label(2, get_axis(range(0, yRange, 40))) 
	graph.axes.label(3, get_axis(termStats)) 

	return graph


def get_avg_age_graph(terms):
	avgAges = []

	for parlament in Group.objects.filter(type__iexact = 'PARLAMENT'):
		avgAges.append(parlament.getAvgAge())

	maxAvg = max(avgAges)
	yRange = ((maxAvg / 10) + 1) * 10
	graph = VerticalBarGroup(map(lambda x: ((x * 1.0)/yRange) * 100.0, avgAges))
	graph.color('777777')
	graph.title(_(u'Prům. věk'))
	graph.axes.type('xxyt')
	startY, endY = get_year_rng_axes(terms)
	graph.axes.label(0, startY)
	graph.axes.label(1, endY)
	graph.axes.label(2, get_axis(range(0, yRange, 10))) 
	graph.axes.label(3, get_axis(avgAges)) 

	return graph


def get_absences_graph(terms):
	absences = []
	presences = []
	for t in terms:
		voteStats = VoteStats.objects.getStatsForTerm(t)
		perc = get_percents(	voteStats.totalAbsences,
								voteStats.presences
						)
		absences.append(math.ceil(perc))
		presences.append(100 - math.floor(perc))

	graph = VerticalBarStack([absences, presences])
	graph.color('770000', '007700')
	graph.legend(_(u'Chybí'), _(u'Přítomno'))
	graph.title(_(u'Absence při hlasování [%]'))
	graph.axes.type('xxty')
	startY, endY = get_year_rng_axes(terms)
	graph.axes.label(0, startY)
	graph.axes.label(1, endY)
	graph.axes.label(2, get_axis(absences)) 

	return graph


def get_absences_pie_graph(term):
	stats = VoteStats.objects.getStatsForTerm(term)
	total = voteStats.presences + voteStats.totalAbsences
	retVal = Pie3D([ 	voteStats.presences / total,
						voteStats.excused / total,
						voteStats.absences / total
					])
	retVal.label(	_(u'Přítomno') + ' %d' % voteStats.presences,
							_(u'Omluveno') + ' %d' % voteStats.excused,
							_(u'Chybí') + ' %d' % voteStats.absences
						)
	retVal.color('00dd00', 'dd7700', 'dd0000') 
	retVal.size(330, 80)

	return retVal


def get_avg_groups(terms):
	mpsInTerm = 0
	memberships = 0
	for t in terms:
		date = None
		groups = Group.objects.filter(term = t)

		for g in groups:
			memberships += Membership.objects.filter(
													group = g,
													post__iregex = '.len'
												).count()

		date = None
		if t.isComplete():
			date = datetime.date(
					year = t.getStart() + (t.getStart() - t.getEnd() / 2),
					month = 2,
					day = 15
				)
		else:
			date = datetime.date.today()

		mpsInTerm += Person.objects.countPersonsForDay(date)

	return memberships / mpsInTerm
		

def get_avg_groups_graph(terms):
	groupStats = []

	for t in terms:
		date = None
		memberships = 0
		mpsInTerm = 0

		for g in Group.objects.filter(term = t):
			memberships += Membership.objects.filter(group = g).count()

		if t.isComplete():
			date = datetime.date(
					year = t.getStart() + ((t.getEnd() - t.getStart()) / 2),
					month = 2,
					day = 15
				)
		else:
			date = datetime.date.today()

		mpsInTerm += Person.objects.countPersonsForDay(date)

		avgGroups = (memberships * 1.0) / (mpsInTerm)
		groupStats.append(avgGroups)

	maxGroup = max(groupStats)
	yRange = ((maxGroup / 10) + 1) * 10
	graph = VerticalBarGroup(map(lambda x: (x/yRange) * 100.0, groupStats))
	graph.color('777777')
	graph.title(_(u'Skupin na poslance'))
	graph.axes.type('xxytt')
	startY, endY = get_year_rng_axes(terms)
	graph.axes.label(0, startY)
	graph.axes.label(1, endY)
	graph.axes.label(2, get_axis(range(0, int(yRange), 5000))) 

	evenGroups = ['%.2f' % groupStats[i]
							for i in range(len(groupStats)) if i % 2 == 0
				]
	oddGroups =  ['%.2f' % groupStats[i]
							for i in range(len(groupStats)) if i % 2 == 1
				]
	graph.axes.label(3, get_axis(evenGroups, 1, 0)) 
	graph.axes.label(4, get_axis(oddGroups, 1, 1)) 

	return graph
		
def get_poll_count_graph(terms):
	pollStats = []

	for t in terms:
		polls = 0
		for m in Meeting.objects.filter(term = t):
			polls += Poll.objects.filter(meeting = m).count()
		pollStats.append(polls)

	maxPollsCount = max(pollStats)
	yRange = ((maxPollsCount / 1000) + 1) * 1000
	yRangeScaled = yRange / 10
	graph = VerticalBarGroup(map(lambda x: ((x * 1.0)/yRange) * 100.0, pollStats))
	graph.color('777777')
	graph.title(_(u'Počet hlasování'))
	graph.axes.type('xxytt')
	startY, endY = get_year_rng_axes(terms)
	graph.axes.label(0, startY)
	graph.axes.label(1, endY)
	graph.axes.label(2, get_axis(range(0, yRange, 5000))) 

	evenPolls = [pollStats[i] for i in range(len(pollStats)) if i % 2 == 0]
	oddPolls =  [pollStats[i] for i in range(len(pollStats)) if i % 2 == 1]
	graph.axes.label(3, get_axis(evenPolls, 1, 0)) 
	graph.axes.label(4, get_axis(oddPolls, 1, 1)) 

	return graph

	
def get_party_age(term):
	records = []
	for club in Group.objects.filter(type__iexact = 'KLUB', term = term):
		record = {}
		record['club'] = club
		record['avgAge'] = club.getAvgAge()
		records.append(record)
		
	gData = []
	colors = []
	for i in records:
		gData.append([ i['avgAge'] ])

	#graph = VerticalBarGroup(gData)
	graph = VerticalBarGroup(map(lambda x: x['avgAge'], records))
	graph.scale(0, 100)
	colors = ''
	for i in records:
		colors += i['club'].color + '|'
	graph.color(colors.strip('|'))
	graph.title(u'Průměrný věk stranických klubů')
	label = [ i['club'].getPartyName() for i in records ]
	evenParties = [ records[i]['club'].getPartyName() for i in range(len(records)) if i % 2 == 0 ]
	oddParties = [ records[i]['club'].getPartyName() for i in range(len(records)) if i % 2 == 1 ]
	graph.axes.type('xxyt')
	graph.axes.label(0, get_axis(evenParties, 1, 0))
	graph.axes.label(1, get_axis(oddParties, 1, 1))
	graph.axes.label(2, get_axis(['0', '20', '40', '60', '80']))
	ages = [ '%.2f' % i['avgAge'] for i in records ]
	graph.axes.label(3, *ages)

	return graph


def show_mp(request, mpSlug):
	mp = get_object_or_404(Person, slug = mpSlug)
	termData = []
	terms = TermOfOffice.objects.all()
	for t in terms:
		record = {
			'term' : t,
			'detail' : None,
			'graph' : mp.getPresencePieChartForTerm(t),
			'mpClubs' : mp.getGroups(t),
		}
		try:
			record['detail'] = PersonDetail.objects.get(
									person = mp,
									term = t
								)
		except ObjectDoesNotExist:
			continue
		termData.append(record)

	mships = mp.getParlMemberships()
	mships = mships.order_by('start')
	
	if mships.count() == 0:
		raise Http404

	dateStart = mships[0].start
	dateEnd = None
	if mships.filter(end = None).count() != 0:
		dateEnd = datetime.date.today()
	else:
		mships = mships.order_by('-end')
		dateEnd = mships[0].end


	return render_to_response('mp_overview.html', {
							'termRecords' : termData,
							'presenceGraphTotal' : mp.getPresencePieChartForTerm(),
							'mp' : mp,
							'justiceKey' : getAuthToken(mp.name + mp.surname),
							'terms' : mp.getTermLinks(),
							'dateStart' : dateStart,
							'dateEnd' : dateEnd,
							},
						context_instance = RequestContext(request)
					)


def index_html(request):
	terms = TermOfOffice.objects.all()
	dateStart = Poll.objects.all().order_by('date')[0].date
	context = cache.get('index.html')
	if context == None:
		context = {
			'dateStart' : dateStart,
			'dateEnd' : datetime.date.today(),
			'firstYear' : terms[0].getStart(),
			'totalPolls' : Poll.objects.all().count(),
			'totalMeetings' : Meeting.objects.all().count(),
			'mpTotal' : Person.objects.all().count(),
			'recycle' : get_recyclation_graph(terms),
			'recycleTrend' : get_recyclation_trend_graph(terms),
			'fmRatio' : get_mf_ratio_graph(terms),
			'mpOrgs' : get_mp_orgs_graph(terms),
			'avgAge' : get_avg_age_graph(terms),
			'avgGroups' : get_avg_groups(terms),
			'avgOrgsMP' : get_avg_groups_graph(terms),
			'absence' : get_absences_graph(terms),
			'polls' : get_poll_count_graph(terms),
			'terms' : TermOfOffice.get_terms_list(),
		}
		cache.set('index.html', context, 24 * 3600)

	return render_to_response('index.html',
							context,
							context_instance = RequestContext(request)
						)



def index_term_html(request, start, end):
	key = 'index_term' + start + end

	context = cache.get(key)

	if context == None:
		term = TermOfOffice.get_term_or_404(start, end)
		totalPolls = 0
		meetings = Meeting.objects.filter(term = term) 
		for m in meetings:
			totalPolls += Poll.objects.filter(meeting = m).count()

		parliament = Group.objects.get(
						type__iexact = 'PARLAMENT',
						term = term
					)

		vs = VoteStats.objects.getStatsForTerm(term)
		total = vs.totalAbsences + vs.presences
		if total == 0:
			total = 1
		total = total * 1.0

		dateStart = Poll.objects.filter(
								meeting__term = term
							).order_by('date')[0].date
		dateEnd = Poll.objects.filter(
								meeting__term = term
							).order_by('-date')[0].date
		context = {
			'term' : term,
			'dateStart' : dateStart,
			'dateEnd' : dateEnd,
			'terms' : term.getTermsList(),
			'totalPolls' : totalPolls,
			'totalMeetings' : meetings.count(),
			'mpTotal' : PersonDetail.objects.filter(term = term).count(),
			'orgCount' : Group.objects.filter(
							term = term
						).count(),
			'avgAge' : parliament.getAvgAge(),
			'mpAge' : get_party_age(term),
			'absences' : '%.2f' % get_percents(vs.totalAbsences, total),
			'recycle' : get_recycled_pie_graph(term),
			'fmRatio' : parliament.getMfPie(),
			'mpClubs' : parliament.getPartyPie(),
			'boards' : Group.objects.filter(
								term = term,
								type__iexact = u'VÝBOR'
							).order_by('origName'),
			'committees' : Group.objects.filter(
								term = term,
								type__exact = u'KOMISE'
							).order_by('origName'),
			'mpuGroups' : Group.objects.filter(
								term = term,
								type__regex = u'.*MPU'
							).order_by('origName'),
			'delegs' : Group.objects.filter(
								term = term,
								type__exact = u'DELEGACE'
							).order_by('origName'),
			'rest' : Group.objects.filter(
								Q(term = term),
								~Q(type__exact = u'DELEGACE'),
								~Q(type__regex = u'.*MPU'),
								~Q(type__iexact = u'KOMISE'),
								~Q(type__iexact = u'KLUB'),
								~Q(type__iregex = u'(POD)?VÝBOR')
							).order_by('origName'),
		}
		cache.set(key, context, 24 * 3600)

	return render_to_response('index_term.html',
								context,
								context_instance = RequestContext(request)
							)


def make_poll_groups(mpVotes):
	retVal = []
	names = mpVotes.distinct('poll_name')

	for name in names:
		list = []
		for pollVotes in mpVotes.filter(poll__name = name.poll.name):
			list.append(pollVotes)
		retVal.append(list)

	return retVal



def show_mp_term(request, mpSlug, start, end):
	term = TermOfOffice.get_term_or_404(start, end)
	date = Poll.objects.filter(
					meeting__term = term
			).order_by('-date')[0].date

	return show_mp_day(	request,
						mpSlug,
						date.year,
						date.month,
						date.day,
						term
					)



def get_date_data_group(group, date):
	"""
	Returns dictionary for group an date. The dictionary contains
	statistics related to particular date and group
	{
		'totalDayPolls' : 0,
		'nextDate' : None,
		'prevDate' : None,
		'acceptedProposals' : 0,
		'refusedProposals' : 0
	}

	"""

	retVal = {
		'totalDayPolls' : 0,
		'nextDate' : None,
		'prevDate' : None,
		'acceptedProposals' : 0,
		'refusedProposals' : 0,
		'groupStats' : None,
	}

	allPolls = Poll.objects.filter(date = date)
	retVal['totalDayPolls'] = allPolls.count()

	if retVal['totalDayPolls'] == 0:
		raise Http404

	retVal['acceptedProposals'] = allPolls.filter(
							verdict__iexact = u'Přijato'
						).count()
	retVal['refusedProposals'] = allPolls.filter(
							verdict__iexact = u'Zamítnuto'
						).count()
	nextDate = None
	prevDate = None
	nextDatePoll = Poll.objects.filter(
						meeting__term = group.term,
						date__gt = date
					).order_by('date')
	prevDatePoll = Poll.objects.filter(
						meeting__term = group.term,
						date__lt = date
					).order_by('-date')

	if nextDatePoll.count() != 0:
		retVal['nextDate'] = nextDatePoll[0].date

	if prevDatePoll.count() != 0:
		retVal['prevDate'] = prevDatePoll[0].date

	dateStart = allPolls[0].date
	groupStats = GroupStats.objects.getStats(group, dateStart = dateStart)
	groupStats.getResultChart()
	retVal['groupStats'] = groupStats

	return retVal
	

def get_date_data(mp, date, term):
	"""
	Returns dictionary for mp, date and term. The dictionary contains
	statistics related to particular date and mp. Dictionary looks as follows:
	{
		'totalDayPolls' : 0,
		'nextDate' : None,
		'prevDate' : None,
		'acceptedProposals' : 0,
		'refusedProposals' : 0,
		'mpAbsences' : 0,
		'mpAye' : 0,
		'mpNay' : 0,
		'mpRefrains' : 0,
		'loaylDayChart': None,
		'mpDayStatChart' : None,
		'currentDate' : None,
	}
	"""
	retVal = {
		'totalDayPolls' : 0,
		'nextDate' : None,
		'prevDate' : None,
		'acceptedProposals' : 0,
		'refusedProposals' : 0,
		'mpAbsences' : 0,
		'mpAye' : 0,
		'mpNay' : 0,
		'mpRefrains' : 0,
		'loaylDayChart': None,
		'mpDayStatChart' : None,
		'currentDate' : None,
	}

	allPolls = Poll.objects.filter(date__lte = date).order_by('-date')
	if allPolls.count() != 0:
		date = allPolls[0].date	
		allPolls = Poll.objects.filter(date = date)
	else:
		raise Http404

	retVal['currentDate'] = date
	retVal['totalDayPolls'] = allPolls.count()
	if retVal['totalDayPolls'] == 0:
		raise Http404

	retVal['acceptedProposals'] = allPolls.filter(
							verdict__iexact = u'Přijato'
						).count()
	retVal['refusedProposals'] = allPolls.filter(
							verdict__iexact = u'Zamítnuto'
						).count()

	nextDate = None
	prevDate = None
	nextDatePoll = Poll.objects.filter(
						meeting__term = term,
						date__gt = date
					).order_by('date')
	prevDatePoll = Poll.objects.filter(
						meeting__term = term,
						date__lt = date
					).order_by('-date')

	if nextDatePoll.count() != 0:
		retVal['nextDate'] = nextDatePoll[0].date

	if prevDatePoll.count() != 0:
		retVal['prevDate'] = prevDatePoll[0].date

	s = mp.getPersonWithStats(date)
	retVal['mpAbsences'] = s.totalAbsences
	retVal['mpAye'] = s.votesAye
	retVal['mpNay'] = s.votesNay
	retVal['mpRefrains'] = s.votesRefrain
	retVal['loyalDayChart'] = mp.getLoyalChartForDates(
									dateStart = date,
									group = mp.getPartyClub(date)
								)
	retVal['mpDayStatChart'] = mp.getStatsChartForDates(date)

	return retVal

	

def show_mp_day(request, mpSlug, year, month, day, term = None):
	"""
	Returns mp_term_overview view for a particular day.  The term is used just
	for show_mp_term() view.
	"""
	date = None

	if type(year) == type(u''):
		date = datetime.date(
						year = int(year),
						month = int(month),
						day = int(day)
					)
	else:
		date = datetime.date(
						year = year,
						month = month,
						day = day
					)
		

	mp = None
	groupMemberships = None

	if term == None:
		term = TermOfOffice.get_term_for_date(date)
	
	if term == None:
		raise Http404

	mp = Person.objects.getPerson(person = mpSlug.lower(), term = term)
	
	if mp == None:
		raise Http404

	groupMemberships = mp.getGroups(term)

	if groupMemberships.count() == 0:
		raise Http404

	term = groupMemberships[0].group.term
	mp.term = term

	mships = []
	for partyMship in mp.getPartyMships(term):
		mships.append(partyMship)

	for mship in groupMemberships:
		if mship.group.type == 'KLUB':
			continue
		mships.append(mship)

	detail = get_object_or_404(
			PersonDetail,
			person = mp,
			term = term
		)

	dateStart = groupMemberships.order_by('start')[0].start
	dateEnd = None
	
	if groupMemberships.filter(end = None).count() != 0:
		dateEnd = datetime.date.today()
	else:
		dateEnd = groupMemberships.order_by('-end')[0].end

	if dateEnd < date:
		date = dateEnd
	
	templateDict = get_date_data(mp, date, term)
	templateDict['dateStart'] = dateStart
	templateDict['dateEnd'] = dateEnd
	templateDict['termLinks'] = mp.getTermLinks(term)
	templateDict['mp'] = mp
	templateDict['mships'] = mships 
	templateDict['partyClubs'] = mp.getPartyMships(term)
	templateDict['parties'] = Group.objects.filter(
								~Q(id = templateDict['partyClubs'][0].group.id),
								term = term,
								type__iexact = 'KLUB'
							)
	templateDict['justiceKey'] = getAuthToken(mp.name + mp.surname)
	templateDict['mpAbsencesPie'] = mp.getPresencePieChartForTerm(term)
	templateDict['loyalChart'] = mp.getLoyalChart(term, group = mp.getPartyClub(date))

	return render_to_response(
						'mp_term_overview.html', 
						templateDict,
						context_instance = RequestContext(request)
					)


def get_group_list(group):
	"""
	Returns dictionary made of groups. The key is group type,
	the value is list of dictionaries:
		{	'type': None,
			'name': None,
		}
	"""
	groupTypes = Group.objects.filter(
									~Q(type__iexact = 'PARLAMENT'),
									~Q(type__iregex = 'VL.DA'),
									term = group.term
								).values('type').distinct()
	
	retVal = {}
	for i in groupTypes:
		groups = Group.objects.filter(
							~Q(id = group.id),
							term = group.term,
							type__iexact = i['type']
						).order_by('name')
		retVal[i['type']] = []
		for g in groups:
			record = {}
			record['type'] = g.type
			record['id'] = g.id

			if g.type == 'KLUB':
				record['name'] = g.getPartyName()
			else:
				record['name'] = g.name

			retVal[i['type']].append(record)
	return retVal


def show_group_day(request, groupSlug, year, month, day):
	group = get_object_or_404(Group, slug = groupSlug)
	date = None

	try:
		if type(year) == int(0):
			date = datetime.date(	year = year,
									month = month,
									day = day
								)
		else:
			date = datetime.date(	year = int(year),
									month = int(month),
									day = int(day)
								)
	except:
		raise Http404

	polls = Poll.objects.all().order_by('-date')
	if polls.count() == 0:
		raise Http404

	dateStart = Poll.objects.filter(
								meeting__term = group.term
							).order_by('date')[0].date
	dateEnd = Poll.objects.filter(
								meeting__term = group.term
							).order_by('-date')[0].date

	mshipStart = Membership.objects.filter(
									group = group
								).order_by(
									'start'
								)[0].start
	
	if mshipStart > dateStart:
		dateStart = mshipStart
	
	templateDict = get_date_data_group(group, date)
	templateDict['currentDate'] = date
	templateDict['membersTotal'] = group.membership_set.all().distinct(
														'person'
													).count()
	templateDict['avgAge'] = group.getAvgAge()
	templateDict['partyPie'] = group.getPartyPie()
	templateDict['group'] = group
	templateDict['term'] = group.term
	templateDict['dateStart'] = dateStart
	templateDict['dateEnd'] = dateEnd
	templateDict['groupPresenceChart'] = group.getPresencePieChart()
	templateDict['groupsByType'] = get_group_list(group)
	return render_to_response('show_group.html',
								templateDict,
								context_instance = RequestContext(request)
							)


def show_group(request, groupSlug):
	polls = Poll.objects.all().order_by('-date')
	date = polls[0].date
	return show_group_day(	request,
							groupSlug,
							date.year,
							date.month,
							date.day
						)


def show_poll(request, pollId):
	poll = get_object_or_404(Poll, id = int(pollId))
	term = poll.meeting.term

	parties = Group.objects.getGroupWithStats(term, Q(type__iexact = 'KLUB'), poll)
	boards = Group.objects.getGroupWithStats(term, Q(type__iexact = u'VÝBOR'), poll)
	mpu = Group.objects.getGroupWithStats(term, Q(type__regex = u'.*MPU'), poll)
	delegs = Group.objects.getGroupWithStats(term, Q(type__iexact = u'DELEGACE'), poll)
	comms = Group.objects.getGroupWithStats(term, Q(type__iexact = u'KOMISE'), poll)
	qObjs = (
		Q(term = poll.meeting.term),
		~Q(type__iexact = u'VLÁDA'),
		~Q(type__exact = u'DELEGACE'),
		~Q(type__regex = u'.*MPU'),
		~Q(type__iexact = u'KOMISE'),
		~Q(type__iexact = u'KLUB'),
		~Q(type__iregex = u'(POD)?VÝBOR'),
		~Q(type__iregex = u'PARLAMENT')
	)
	rest = Group.objects.getGroupWithStatsArg(poll, qObjs)
	
	return render_to_response('show_poll.html', {
									'pie' : poll.resultPie(),
									'poll' : poll,
									'year' : poll.date.year,
									'month' : poll.date.month,
									'partyClubs' : parties,
									'boards' : boards,
									'mpuGroups' : mpu,
									'delegs' : delegs,
									'committees' : comms,
									'rest' : rest,
									'parlament' : Group.objects.get(
														type = u'PARLAMENT',
														term = term
													),
								},
								context_instance = RequestContext(request)
							)

def show_poll_for_mp(request, pollId, mpSlug):
	return render_to_response('show_mp_poll.html', {
									'mp' : get_object_or_404(Person, slug = mpSlug),
								},
								context_instance = RequestContext(request)
							)


def show_day_polls(request, year, month, day):
	date = datetime.datetime(
						year = int(year),
						month = int(month),
						day = int(day)
					)
	pollQS = get_list_or_404(Poll, date = date)
	poll = pollQS[0]

	return render_to_response('show_day_polls.html', {
									'pollDate' : date,
									'poll' : poll,
									'year' : date.year,
									'month' : date.month,
								},
								context_instance = RequestContext(request)
							)


def show_about(request):
	"""
	This is a dummy page, which will generate some
	data about web (about page in czech)
	"""
	return render_to_response('about.html', {},
								 context_instance = RequestContext(request)
							)

